package com.cheng.student.dao;

import com.cheng.student.beans.Student;
import com.cheng.student.beans.StudentFull;
import com.cheng.student.dao.mappers.StudentMapper;
import com.cheng.student.utils.SqlSessionGetter;
import org.apache.ibatis.exceptions.PersistenceException;

import org.apache.ibatis.session.SqlSession;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class StudentDao
{
    public static void main(String[] args)
            throws NoSuchFieldException, IllegalAccessException
    {
        SqlSession sqlSession = SqlSessionGetter.getSqlSession();

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        System.out.println(mapper.updateStudentByNameNumber("zhangsan", "123", "ksh", "234"));
    }

    public static List<StudentFull> selectStudentFulls(
            String area ,
            String gender,
            String academy,
            String major,
            String batch,
            String type,
            int start,
            int end)
    {
        SqlSession sqlSession = SqlSessionGetter.getSqlSession();

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        List<StudentFull> studentFulls = mapper.selectStudentFulls(
                area,gender,academy,major,batch,type,start,end - start + 1);

        return studentFulls;
    }

    //根据姓名与考生号查询具体学生
    public static Student getStudent(String name, String number)
    {

        SqlSession sqlSession = SqlSessionGetter.getSqlSession();

        //mybatis自动封装的mapper对象
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

        Student student = studentMapper.selectStudentByNameNumber(name,number);
        sqlSession.close();

        return student;
    }

    //添加学生

    public static void insertStudents(List<StudentFull> students)
            throws InsertFailedException
    {
        SqlSession sqlSession = SqlSessionGetter.getSqlSession();

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        boolean isSuccess = true;
        //开启事务
        mapper.startTransaction();

        for (StudentFull student: students)
        {
            try
            {
                if(0 == mapper.insertStudentFull(student))
                {
                    throw new Exception();
                }
            }
            catch (Exception e)
            {
                //添加失败回滚
                mapper.rollBack();
                //通过这个exception储存出错的学生交给上一层处理
                throw new InsertFailedException(student);
            }
        }
        //提交
        mapper.commit();
        return;
    }

}
